package com.liuc.mybatis;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {

    private Map <String,Object > map = new HashMap<>();

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public void put(String key,Object value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t写入数据");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t写入完成");
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }
    public void get(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t读取数据");
            Object object = map.get(key);
            System.out.println(Thread.currentThread().getName()+"\t读取完成"+object);
        }finally {
            readWriteLock.readLock().unlock();
        }
    }

    public static void main(String[] args) {
        ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();
        for(int i=1; i<=6; i++){
            int finalI = i;
            new Thread(() ->{
                readWriteLockDemo.put(finalI+"", finalI);
            },String.valueOf(i)).start();
        }
        for(int i=1; i<=6; i++){
            int finalI = i;
            new Thread(() ->{
                readWriteLockDemo.get(finalI+"");
            },String.valueOf(i)).start();
        }
    }

}
